from pymodbus.client.tcp import ModbusTcpClient
import time

# 配置 Modbus 服务器的 IP 地址和端口号
MODBUS_SERVER_IP = "192.168.1.199"  # 替换为目标设备的 IP 地址
MODBUS_SERVER_PORT = 502  # 默认的 Modbus TCP 端口号

# 配置寄存器的地址和需要写入的值
REGISTER_ADDRESS =0  # 寄存器地址

# 创建 Modbus 客户端实例
client = ModbusTcpClient(MODBUS_SERVER_IP, port=MODBUS_SERVER_PORT)

def write_register(key,value):
    """向寄存器写入值"""
    try:
        # 写入单个寄存器
        response = client.write_registers(key, value)
        if response.isError():
            print(f"写入失败: {response}")
        else:
            print(f"成功写入寄存器 {REGISTER_ADDRESS} 值: {value}")
    except Exception as e:
        print(f"发生错误: {e}")

def main():
    # 连接Modbus设备
    if not client.connect():
        print("无法连接到Modbus设备")
        return

    try:
        result = client.read_holding_registers(address=3, count=1, unit=1)
        print("急停信号:",result.registers[0])

        while result.registers[0]==0:
            # 写入1
            write_register(2,1)
            write_register(1, 1)
            time.sleep(3)  # 等待1秒

            # 写入0
            write_register(2,0)
            write_register(1,0)

            time.sleep(3)  # 等待1秒

    except KeyboardInterrupt:
        print("程序已停止")
    finally:
        # 关闭连接
        client.close()

if __name__ == "__main__":
    main()